package com.it.bannner

import android.view.LayoutInflater
import android.view.ViewTreeObserver
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import chuangyuan.ycj.videolibrary.listener.VideoInfoListener
import chuangyuan.ycj.videolibrary.video.VideoPlayerManager
import com.haiheng.bookmusic.base.BaseActivity
import com.it.bannner.common.Message
import com.it.bannner.databinding.ActivityMainLandBigBinding
import com.it.bannner.databinding.ActivityMainLandBinding
import com.it.bannner.log.LogWriter
import com.it.bannner.utils.DisplayUtil
import com.it.bannner.utils.QrCodeGenerator
import com.it.bannner.video.MyDataSource
import com.it.bannner.view.RecyclerViewSpacesItemDecoration
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import layout.PaymentAdapter
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File


class MainLanBigActivity : BaseActivity(), VideoInfoListener {


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(msg: Message) {
        //下载完成了
        if (msg.downLoadFinishMsg != null) {
            val name = msg.downLoadFinishMsg.name
            lifecycleScope.launch {
                //查询
                val result = viewModel?.queryListByName(name)
                result?.downed = 1
                //更新
                result?.let { viewModel?.updateRecord(it) }
            }

        }

    }


    var activityMainBinding: ActivityMainLandBigBinding? = null


    override fun initDataChange() {
        //获取视频数据
        viewModel?.videoList?.observe(this, Observer {
            if (it.code == 0 && it.data?.size!! > 0) {
                playUriList.clear()
                playUriList.addAll(it.data!!)
                LogWriter.e("视频长度: " + it.data!!.size)
                index = 0
                tryPlay()
                sysData()

            } else {
                tryPlay()
                LogWriter.e("视频异常信息: " + it.msg)
            }

        })
        viewModel?.deviceInfoDto?.observe(this, Observer {
            if (it.code == 0 && it.data != null) {

                //设置音量

                val result = it.data
                setAudio(result?.Volume)
                LogWriter.e("获取设备信息: " + result)
                val code = result?.AppVersion?.VersionCode
                LogWriter.e("从服务器获取的版本${code}")
                code?.let {
                    LogWriter.e("当前版本${getVersionCode()}")
                    if(code>getVersionCode()){
                        LogWriter.e("服务器版本大于当前版本")
                        val path = result?.AppVersion?.AppUrl
                        LogWriter.e("服务器返回的下载地址 ${path}")
                        LogWriter.e("开始下载 ${path}")
                        startDownLoadApkTask(path)
                    }
                    else{
                        LogWriter.e("服务器版本小于当前版本")
                    }

                }
                activityMainBinding?.price?.text = result?.Price
                paymentList.clear()
                it?.data?.PaymentIcon?.let { it1 -> paymentList.addAll(it1) }
                adapter?.notifyDataSetChanged()


                val bitmap = QrCodeGenerator.generateBitmap(
                    it?.data?.QRCode,
                    DisplayUtil.dip2px(this, 160f),
                    DisplayUtil.dip2px(this, 160f), true
                )
                activityMainBinding?.ivCode?.setImageBitmap(bitmap)
                activityMainBinding?.title?.text = it?.data?.Title
                activityMainBinding?.paymentTitle?.text = it?.data?.PaymentTitle
                activityMainBinding?.tvHotel?.text = "HOTLINE:${it?.data?.CusSvstel}"


            } else {
                LogWriter.e("设备异常信息: " + it.msg)
            }
        })
    }


    override fun initView() {
        activityMainBinding?.tvVersion?.text = "VersionName:${getVersionName()}"
        val vto = activityMainBinding?.exoPlayContextId?.getViewTreeObserver()
        EventBus.getDefault().register(this)
        exoPlayerManager = VideoPlayerManager.Builder(
            VideoPlayerManager.TYPE_PLAY_GESTURE,
            activityMainBinding?.exoPlayContextId!!
        )
            .setDataSource(MyDataSource(this))
            .setShowVideoSwitch(true)
            .addVideoInfoListener(this)
            .create()
        activityMainBinding?.recyclerView?.layoutManager = GridLayoutManager(this, 2)
        adapter = PaymentAdapter(R.layout.item_payment_land, paymentList)
        activityMainBinding?.recyclerView?.adapter = adapter

        val map = HashMap<String, Int>()
        map.put(
            RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION,
            DisplayUtil.dip2px(this, 8f)
        )


        val decoration = RecyclerViewSpacesItemDecoration(map)
        activityMainBinding?.recyclerView?.addItemDecoration(
            decoration
        )

        activityMainBinding?.exoPlayContextId?.setVerticalFullScreen(false)
        //全屏按钮
        val checkBox = activityMainBinding?.exoPlayContextId?.getExoFullscreen()
        checkBox?.setOnClickListener {

        }
        activityMainBinding?.exoPlayContextId?.playerView?.controller?.playButton?.isEnabled = false
        activityMainBinding?.exoPlayContextId?.playerView?.controller?.pauseButton?.isEnabled =
            false

    }

    override fun onDestroy() {
        exoPlayerManager?.onDestroy()
        if (intentService != null) {
            stopService(intentService)
        }

        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    override fun intiLayout() {
        activityMainBinding = ActivityMainLandBigBinding.inflate(LayoutInflater.from(this))
        setContentView(activityMainBinding?.getRoot())
    }

    private fun tryPlayCatch() {
        lifecycleScope.launch(Dispatchers.Main)
        {
            cacheUriList = viewModel.queryList()
            LogWriter.e("尝试查询缓存记录 = ${cacheUriList}")
            cacheUriList?.let {
                LogWriter.e("播放缓存的${it[index].path}")
                activityMainBinding?.url?.text = "播放缓存的:${it[index].path}"
                it[index].path?.let { it1 -> exoPlayerManager?.setPlayUri(it1) }
                exoPlayerManager?.startPlayer()
            }


        }

    }

    override fun tryPlay() {
        if (playUriList == null || playUriList.size <= 0) {
            tryPlayCatch()
        } else {
            lifecycleScope.launch(Dispatchers.Main)
            {
                val url = playUriList[index]
                LogWriter.e("所有的url:${playUriList}")
                LogWriter.e("当前播放url:${url}")
                val array = url.split("/")
                val name = array[array.size - 1]
                val result = viewModel?.queryListByName(name)
                if (result != null && result.downed == 1) {
                    val file = File(result?.path)
                    //没有这个文件
                    if (file == null) {
                        LogWriter.e("本地文件不存在，播放在线的${url}")
                        activityMainBinding?.url?.text = "播放在线的:${url}"
                        exoPlayerManager?.setPlayUri(url)
                    } else {
                        LogWriter.e("播放缓存的${result?.path}")
                        activityMainBinding?.url?.text = "播放缓存的:${result?.path}"
                        result.path?.let { exoPlayerManager?.setPlayUri(it) }
                    }
                } else {
                    LogWriter.e("数据库记录没有下载完成，播放在线的${url}")
                    activityMainBinding?.url?.text = "播放在线的:${url}"
                    exoPlayerManager?.setPlayUri(url)
                }
                exoPlayerManager?.startPlayer()

            }
        }

    }


    override fun isPlaying(playWhenReady: Boolean) {
        LogWriter.e("isPlaying: ...")
        activityMainBinding?.exoPlayContextId?.playerView?.controller?.playButton?.isEnabled = true
        activityMainBinding?.exoPlayContextId?.playerView?.controller?.pauseButton?.isEnabled = true
    }

    override fun updateId(id: String?) {
        activityMainBinding?.tvVersion?.text = "DeviceId:${id}  VersionName:${getVersionName()}"
    }
}